package com.nononsenseapps.feeder.sync.local.source.dir

import android.content.Context
import android.text.Html
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import com.nononsenseapps.feeder.db.DEFAULT
import com.nononsenseapps.feeder.util.GsFileUtils
import com.nononsenseapps.feeder.util.GsFileUtils.MimeType_Markdown
import com.nononsenseapps.feeder.parser.Attachment
import com.nononsenseapps.feeder.parser.Author
import com.nononsenseapps.feeder.parser.Feed
import com.nononsenseapps.feeder.parser.Item
import org.commonmark.ext.front.matter.YamlFrontMatterExtension
import org.commonmark.ext.front.matter.YamlFrontMatterNode
import org.commonmark.node.Node
import org.commonmark.parser.Parser
import org.joda.time.LocalDateTime
import timber.log.Timber
import java.io.InputStreamReader
import java.util.*


object DirSource {
    const val DIR_PATH="/dir/"

    const val STORAGE_EMULATED_0 = "/storage/emulated/0"
    const val STORAGE_EMULATED_0_ANDROID = "/storage/emulated/0/Android"
    const val STORAGE_EMULATED_0_ANDROID_DATA = "/storage/emulated/0/Android/data"
    const val STORAGE_EMULATED_0_ANDROID_OBB = "/storage/emulated/0/Android/obb"

    const val MARKDOWN_FILE_ID="feedin_id"
    const val MARKDOWN_FILE_TITLE="feedin_title"
    const val MARKDOWN_FILE_TAGS="feedin_tags"
    const val MARKDOWN_FILE_ENCLOSURE="feedin_enclosure"
    const val MARKDOWN_FILE_AUTHOR="feedin_author"

    val extensions= listOf(YamlFrontMatterExtension.create())
    val parser: Parser = Parser.builder()
        .extensions(extensions)
        .build()

    suspend fun fetchFeedForDir(feedSql: com.nononsenseapps.feeder.db.entity.Feed,
                                context: Context,
                                pathUriString: String
    ): Feed?{
        var builderFeed: Feed?=null
        val feedItems= mutableListOf<Item>()

        val pathUri= Html.fromHtml(pathUriString,Html.FROM_HTML_MODE_LEGACY).toString().toUri()
        //val realDirPath = GsFileUtils.getRealFilePathFromUri4after(context,pathUri)

        val feedUrl= buildUrl(pathUriString)

        val dir= DocumentFile.fromTreeUri(context,pathUri)
        val mdList= mutableListOf<DocumentFile>()

       Timber.d("come in dir:$pathUriString")

        if(dir?.isDirectory == true){
            listMd(dir,mdList)
            var doc: Node
            var feedItemId:String?=null
            var feedItemTitle:String=""
            var tags:List<String>?=null
            var enclosure: Attachment?=null
            var author: Author?=null
            mdList.forEach {
                val mdBody = InputStreamReader(context.contentResolver.openInputStream(it.uri)).readText()
                doc = parser.parse(mdBody)
                Timber.d("doc name:$doc")
                var node=doc.firstChild
                it.name?.let {name->
                   feedItemTitle=name
                }
                do {
                    Timber.d("node name:$node")
                    if (node is YamlFrontMatterNode) {
                        when(node.key){
                            MARKDOWN_FILE_ID-> feedItemId = node.values[0]
                            MARKDOWN_FILE_TITLE -> feedItemTitle = node.values[0]
                            MARKDOWN_FILE_TAGS -> tags = node.values
                            MARKDOWN_FILE_ENCLOSURE -> enclosure = Attachment(node.values[0])
                            MARKDOWN_FILE_AUTHOR -> author = Author(node.values[0])
                            else->{}
                        }
                    }
                    node=node.next
                }while(node!=null)

                val strDate = LocalDateTime.fromDateFields(Date(it.lastModified())).toString()


                if(feedItemId.isNullOrEmpty())
                    feedItemId = it.uri.toString()

                Timber.d("come in dir:$pathUriString item id:$feedItemId")

                val itemUrl = "$feedUrl&id=$feedItemId"

                feedItems.add(
                    Item(
                    id=feedItemId,
                    title = feedItemTitle,
                    url= itemUrl,
                    content_html=mdBody,
                    tags=tags,
                    author = author,
                    date_published=strDate,
                    date_modified =strDate,
                    attachments = if(enclosure!=null) listOf(enclosure!!) else null
                )
                )
            }

            builderFeed = Feed(
                title=dir.name,
                feed_url=feedUrl,
                items=feedItems,
                responseHash = UUID.randomUUID().hashCode()
            )
        }
        return builderFeed
    }

    private fun listMd(parentDir:DocumentFile, mdFileList: MutableList<DocumentFile>){
       /*val dirList=parentDir.listFiles
        val mdList=parentDir.listFiles(object: FileFilter {
            override fun accept(pathname: File?): Boolean {
                pathname?.let {
                    return it.isFile&&GsFileUtils.getMimeType(it).equals(MimeType_Markdown)
                }
                return false
            }
        })
        mdFileList.addAll(mdList)
        dirList.forEach {
            listMd(it,mdFileList)
        }*/
        parentDir.listFiles().forEach { file->
            if(file.isDirectory){
                listMd(file,mdFileList)
            }else if(file.isFile){
                Timber.d("list type:${file.type}\tname:${file.name}\t isFile:${file.isFile}")
                if(GsFileUtils.getMimeType(file.name)==MimeType_Markdown){
                    mdFileList.add(file)
                }
            }
        }
    }


    fun buildUrl(pathName:String)= DEFAULT.SOURCE_URL+DIR_PATH+"?"+pathName

}